package db

import (
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gysa-share01/common"
	"gysa-share01/models/order"
	"gysa-share01/models/user"
	"os"
	"time"
)

var (
	dbInstance  *gorm.DB
	hasInstance = false
)

func Instance(...interface{}) (db *gorm.DB, err error) {
	if hasInstance {
		db = dbInstance
		return
	}
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	host := os.Getenv("MYSQL_HOST")
	port := os.Getenv("MYSQL_PORT")
	dnName := os.Getenv("MYSQL_DB")
	username := os.Getenv("MYSQL_USERNAME")
	password := os.Getenv("MYSQL_PASSWORD")
	if host == "" || port == "" || dnName == "" {
		err = errors.New("未配置数据库")
		return
	}
	newLogger := logger.New(
		common.Logger,
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // Log level
			Colorful:      false,       // 禁用彩色打印
		},
	)
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, dnName)
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		err = errors.New(fmt.Sprintf("数据库连接失败:%s", err))
		return
	}
	sqlDB, err := db.DB()
	if err != nil {
		err = errors.New(fmt.Sprintf("Gorm error:%s", err))
		return
	}
	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(5)

	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(10)

	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(time.Hour)
	dbInstance = db
	hasInstance = true
	return
}

func AutoMigrate(db *gorm.DB) (err error) {
	migrateModels := []interface{}{
		&user.User{},
		&order.Order{},
	}

	return db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(migrateModels...)

}
